#include "stdafx.h"
#include "HookCore.h"
#include <Windows.h>
#include <stdio.h>

HookProc UserMouseHookCallback = NULL;
HHOOK mouseHookInstance = NULL;
HINSTANCE hInstance = NULL;
void* userDataPtr = NULL;

LRESULT CALLBACK MouseHookCallback(int code, WPARAM wparam, LPARAM lparam);

HOOKRESULT InitializeHook(HookProc proc)
{
	if(proc == NULL)
		return HookResultCodes::INVALID_ARGUMENT;
	if(UserMouseHookCallback != NULL)
		return HookResultCodes::ALREADY_INITIALIZED;

	UserMouseHookCallback = proc;
	return HookResultCodes::OK;
}

HOOKRESULT StartHook(int threadID, void* userData)
{
	if(hInstance == NULL)
		return HookResultCodes::NOT_ATTACHED;
	if(UserMouseHookCallback == NULL)
		return HookResultCodes::NOT_INITIALIZED;
	if(mouseHookInstance != NULL)
		return HookResultCodes::ALREADY_STARTED;

	userDataPtr = userData;

	mouseHookInstance = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)MouseHookCallback, hInstance, threadID);
	if(mouseHookInstance == NULL)
		return GetLastError();
	return HookResultCodes::OK;
}

HOOKRESULT StopHook()
{
	if(mouseHookInstance == NULL)
		return HookResultCodes::NOT_STARTED;

	if(UnhookWindowsHookEx(mouseHookInstance) == 0)
	{
		return GetLastError();
	}

	mouseHookInstance = NULL;
	return HookResultCodes::OK;	
}

HOOKRESULT UninitializeHook()
{
	UserMouseHookCallback = NULL;
	return HookResultCodes::OK;
}

LRESULT CALLBACK MouseHookCallback(int code, WPARAM wparam, LPARAM lparam)
{
	if(code < 0)
		return CallNextHookEx(mouseHookInstance, code, wparam, lparam);

	if(UserMouseHookCallback != NULL)
	{
		if(UserMouseHookCallback(code, wparam, lparam, userDataPtr) == FALSE)
			return -1;
	}

	return CallNextHookEx(mouseHookInstance, code, wparam, lparam);
}


